//
//  CYSettingsViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/16.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYSettingsViewController.h"

#import "CYSettingsCell.h"
#import "CYSettingsSwitchCell.h"
#import "CYEmptyCell.h"

#import "CYDataAPIUserAccountModel.h"

#import "CYCardListViewController.h"
#import "CYCertificationInfoViewController.h"
#import "CYFindPasswordViewController.h"
#import "CYMainController.h"
#import "CYWebViewController.h"
#import "CYSudokuOpenViewController.h"
#import "CYSudokuCloseViewController.h"
#import "CYSudokuModifyViewController.h"

#import "CYAuthManager.h"
#import "CYPublicParameters.h"



@interface CYSettingsViewController ()

@property(nonatomic, strong)CYSettingsCellObject *certificationCell;
@property(nonatomic, strong)CYSettingsCellObject *bindCardCell;
@property(nonatomic, strong)CYSettingsCellObject *bindMobileCell;
@property(nonatomic, strong)CYSettingsCellObject *evaluateCell;
@property(nonatomic, strong)CYSettingsCellObject *resetPasswordCell;
@property(nonatomic, strong)CYSettingsSwitchCellObject *sudokuSwitchCell;
@property(nonatomic, strong)CYSettingsCellObject *sudokuEditCell;

@property(nonatomic, strong)UIButton *signOutButton;

@property(nonatomic, strong)CYDataAPIUserAccountModel *model;

@end


@implementation CYSettingsViewController

- (void)close
{
    [MobClick event:UM_EVENT_0054];
    [super close];
}

- (void)loadUI
{
    self.navigationItem.title = @"设置";
    
    self.tableView.cy_autoLockVertical = YES;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 10)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 124)];
    {
        self.signOutButton = [UIButton cy_mainButtonWithTitle:@"退出登录"];
        [self.signOutButton setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(1, 1)] forState:UIControlStateNormal];
        [self.signOutButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"ECECEC") size:CGSizeMake(1, 1)] forState:UIControlStateHighlighted];
        [self.signOutButton setTitleColor:APP_DEFAULT_COLOR_RED forState:UIControlStateNormal];
        self.signOutButton.layer.borderWidth = 1 / SCREEN_SCALE;
        self.signOutButton.layer.borderColor = HEXCOLOR(@"ECECEC").CGColor;
        [self.signOutButton addTarget:self action:@selector(onSignOutButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.tableView.tableFooterView addSubview:self.signOutButton];
    }
    [self initCells];
    [self loadCells];
}

- (void)loadData
{
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:CYSudokuPasswordStatesChanged object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x) {
        @strongify(self);
        [self loadCells];
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

- (void)loadDataFromServer
{
    if(self.model == nil)
    {
        [SVProgressHUD show];
    }
    @weakify(self);
    [CYStandardDataAPI user_userAccountWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            self.model = [CYDataAPIUserAccountModel mj_objectWithKeyValues:response.content];
            if(SAFE_STRING(self.model.realName).length && SAFE_STRING(self.model.cardNo).length)
            {
                self.certificationCell.content = SAFE_STRING(self.model.realName).cy_maskName;
                self.certificationCell.hasArrow = YES;
            }
            else
            {
                self.certificationCell.content = @"未实名";
                self.certificationCell.hasArrow = NO;
            }
            if(SAFE_NUMBER(self.model.bankCardNum).integerValue > 0)
            {
                self.bindCardCell.content = @"已绑定";
            }
            else
            {
                self.bindCardCell.content = @"未绑定";
            }
            self.bindMobileCell.content = SAFE_STRING(self.model.mobile).cy_maskPhoneNumber;
            
            NSArray *types = @[@"保守型", @"稳健型", @"平衡型", @"积极型", @"激进型"];
            if(self.model.type.integerValue > 0 && self.model.type.integerValue < 6)
            {
                self.evaluateCell.hasArrow = NO;
                self.evaluateCell.content = types[self.model.type.integerValue - 1];
            }
            else
            {
                self.evaluateCell.hasArrow = YES;
                self.evaluateCell.content = @"";
            }
            
            [self.tableView reloadData];
            
            [SVProgressHUD dismiss];
        }
        else
        {
            if(self.model == nil)
            {
                [SVProgressHUD showErrorWithStatus:response.message];
            }
            else
            {
                [SVProgressHUD dismiss];
            }
        }
    }];
}

- (void)layoutUI
{
    self.tableView.tableFooterView.width = self.tableView.width;
    {
        self.signOutButton.width = self.tableView.tableFooterView.width - 40;
        self.signOutButton.height = 44;
        self.signOutButton.centerY = self.tableView.tableFooterView.height / 2;
        self.signOutButton.centerX = self.tableView.tableFooterView.width / 2;
    }
}

#pragma mark - Actions
- (void)cardAction
{
    CYCardListViewController *cardListViewController = [[CYCardListViewController alloc] init];
    [self.navigationController pushViewController:cardListViewController animated:YES];
}

- (void)certificationAction
{
    CYCertificationInfoViewController *certificationInfoViewController = [[CYCertificationInfoViewController alloc] init];
    certificationInfoViewController.name = SAFE_STRING(self.model.realName).cy_maskName;
    certificationInfoViewController.idNumber = SAFE_STRING(self.model.cardNo).cy_maskIDNumber;
    [self.navigationController pushViewController:certificationInfoViewController animated:YES];
}

- (void)signOutAction
{
    [CYStandardDataAPI user_logoutWithComplete:nil];
    CYStandardAuthManager.currentAuth = nil;
    [CYStandardAuthManager saveAuth];
    [[CYMainController standardController] goHome];
}

- (void)resetPasswordAction
{
    CYFindPasswordViewController *findPasswordViewController = [[CYFindPasswordViewController alloc] init];
    findPasswordViewController.navigationItem.title = @"修改登录密码";
    [self.navigationController pushViewController:findPasswordViewController animated:YES];
}

- (void)evaluateAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/risk_exam.html?from=2"];
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)openSudokuAction
{
    CYSudokuOpenViewController *sudokuOpenViewController = [[CYSudokuOpenViewController alloc] init];
    @weakify(self);
    sudokuOpenViewController.complete = ^{
        @strongify(self);
        [self loadCells];
    };
    [self.navigationController pushViewController:sudokuOpenViewController animated:YES];
}

- (void)closeSudokuAction
{
    CYSudokuCloseViewController *sudokuCloseViewController = [[CYSudokuCloseViewController alloc] init];
    @weakify(self);
    sudokuCloseViewController.complete = ^{
        @strongify(self);
        [self loadCells];
    };
    [self.navigationController pushViewController:sudokuCloseViewController animated:YES];
}

- (void)editSudokuAction
{
    CYSudokuModifyViewController *sudokuModifyViewController = [[CYSudokuModifyViewController alloc] init];
    [self.navigationController pushViewController:sudokuModifyViewController animated:YES];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    id cellObject = [self.tableModel objectAtIndexPath:indexPath];
    if(cellObject == self.bindCardCell)
    {
        [MobClick event:UM_EVENT_0055];
        [self cardAction];
        return;
    }
    if(cellObject == self.certificationCell && self.certificationCell.hasArrow)
    {
        [self certificationAction];
        return;
    }
    if(cellObject == self.resetPasswordCell)
    {
        [MobClick event:UM_EVENT_0057];
        [self resetPasswordAction];
        return;
    }
    if(cellObject == self.evaluateCell && self.evaluateCell.hasArrow)
    {
        [MobClick event:UM_EVENT_0056];
        [self evaluateAction];
        return;
    }
    if(cellObject == self.sudokuEditCell)
    {
        [self editSudokuAction];
        return;
    }
}

#pragma mark - Control Events
- (void)onSignOutButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0058];
    @weakify(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出登录" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self signOutAction];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - Private Method
- (void)initCells
{
    {
        self.certificationCell = [CYSettingsCellObject objectWithCellClass:[CYSettingsCell class]];
        self.certificationCell.title = @"实名认证";
        self.certificationCell.hasArrow = YES;
    }
    {
        self.bindCardCell = [CYSettingsCellObject objectWithCellClass:[CYSettingsCell class]];
        self.bindCardCell.title = @"我的银行卡";
        self.bindCardCell.hasArrow = YES;
    }
    {
        self.bindMobileCell = [CYSettingsCellObject objectWithCellClass:[CYSettingsCell class]];
        self.bindMobileCell.title = @"绑定手机";
        self.bindMobileCell.hasArrow = NO;
    }
    {
        self.evaluateCell = [CYSettingsCellObject objectWithCellClass:[CYSettingsCell class]];
        self.evaluateCell.title = @"风险评测";
        self.evaluateCell.hasArrow = YES;
    }
    {
        self.resetPasswordCell = [CYSettingsCellObject objectWithCellClass:[CYSettingsCell class]];
        self.resetPasswordCell.title = @"修改登录密码";
        self.resetPasswordCell.hasArrow = YES;
    }
    {
        @weakify(self);
        self.sudokuSwitchCell = [CYSettingsSwitchCellObject objectWithCellClass:[CYSettingsSwitchCell class]];
        self.sudokuSwitchCell.title = @"手势登录密码";
        self.sudokuSwitchCell.switchAtion = ^(BOOL on) {
            @strongify(self);
            if(on)
            {
                [self openSudokuAction];
            }
            else
            {
                [self closeSudokuAction];
            }
        };
    }
    {
        self.sudokuEditCell = [CYSettingsCellObject objectWithCellClass:[CYSettingsCell class]];
        self.sudokuEditCell.title = @"修改手势密码";
        self.sudokuEditCell.hasArrow = YES;
    }
}

- (void)loadCells
{
    NSMutableArray *cells = [NSMutableArray array];
    
    {
        [cells addObject:self.certificationCell];
    }
    {
        [cells addObject:self.bindCardCell];
    }
    {
        [cells addObject:self.bindMobileCell];
    }
    {
        [cells addObject:self.evaluateCell];
    }
    {
        CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
        cell.height = 10;
        [cells addObject:cell];
    }
    {
        [cells addObject:self.resetPasswordCell];
    }
    {
        self.sudokuSwitchCell.on = [CYSudokuManager sudokuPassword] != nil;
        [cells addObject:self.sudokuSwitchCell];
    }
    if(self.sudokuSwitchCell.on)
    {
        [cells addObject:self.sudokuEditCell];
    }
    
    
    self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
    self.tableView.dataSource = self.tableModel;
    [self.tableView reloadData];
}

@end
